module.exports = app => {
    const Router = require("koa-router")
    const router = new Router()
    const User = require("../db/user")
    const bodyParser = require("koa-bodyparser") //bodyparser 要用在router之前
    app.use(bodyParser())
    app.use(router.routes()).use(router.allowedMethods())
    
    router.get('/user', async ctx => {
        const res = await User.find().populate('cars').lean() //使用.lean()直接关联查询子级虚拟字段 即显示所有字段
            ctx.body = {
                message: "获取成功",
                status: 200,
                data: res
            }
    })
    router.post('/user', async ctx =>{
        const res = (await User.find({ name: ctx.request.body.name }))||[]
        if(res.length) {
            ctx.body = {
                message: "添加失败！该名称已存在",
                status: 400,
            }
        } else {
            await User.create(ctx.request.body)
            const res = await User.find()
            ctx.body = {
                message: "添加成功",
                status: 200,
                data: res
            }
        }
    })
}